﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using scheduleMVC.Models;
using scheduleMVC.DAL;
using AppLimit.CloudComputing.SharpBox;
using AppLimit.CloudComputing.SharpBox.StorageProvider.DropBox;
using System.IO;
using Microsoft.Live;
using System.Web.Security;
using Microsoft.AspNet.Identity;

namespace scheduleMVC.Controllers
{
    [Authorize(Roles = "Administrator, Employee,FrontDesk,SuperAdmin,Customer")]
    public class TaskController : Controller
    {
        private TasksContext db = new TasksContext();
        private ApplicationDbContext db2 = new ApplicationDbContext();
        private CustomerContext db3 = new CustomerContext();
        private FileContext db4 = new FileContext();

        // GET: /Task/
        public ActionResult Index(string Message)
        {

            
            
            if (User.IsInRole("Administrator"))
            {
                var tasks = db.Tasks.Include(t => t.Customer).Include(t => t.Employee).Include(t => t.Files);
                if (Message != null)
                    ViewBag.message = Message;
                else
                    ViewBag.message = "All Tasks for:" + User.Identity.Name;

                return View(tasks.ToList());
            }
            else
            {
                string currentuserID = User.Identity.GetUserId().ToString();
                var tasks = db.Tasks.Include(t => t.Customer).Include(t => t.Employee).Include(t => t.Files).Where(a => a.Employee.UserId == currentuserID ||  a.Customer.UserId == currentuserID);
                if (Message != null)
                    ViewBag.message = Message;
                else
                    ViewBag.message = "All Tasks for:" + User.Identity.Name;

                return View(tasks.ToList());
            }

          
        }

        // GET: /Task/Details/5
        public ActionResult Details(string id)
        {

            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            TasksModel tasksmodel = db.Tasks.Find(id);
            if (tasksmodel == null)
            {
                return HttpNotFound();
            }

            return View(tasksmodel);
            //return RedirectToAction("Name of the action","Name of the controller");
        }

        // GET: /Task/Create
        public ActionResult Create()
        {
            GetCustomers();//get the customer first name + Last name + Business name
            GetEmployees();//get the Employee first name + Last name 
            GetTasksStatus();
            GetPriorities();
            
            return View();
        }


        private void GetTasksStatus()
        {
            IEnumerable<SelectListItem> TaskS;
            TaskS = new[]
                  {
                    new SelectListItem { Value = "1", Text = "Not Started" },
                    new SelectListItem { Value = "2", Text = "In Progress" },
                    new SelectListItem { Value = "3", Text = "Completed" },
                    new SelectListItem { Value = "4", Text = "Deferred" },
                    new SelectListItem { Value = "5", Text = "Waiting on someone else" }
                  };
            ViewBag.TasksStatus = TaskS;

        }

        private void GetFiles(string id)
        {

            TempData["Filemodel"] = db4.Files.Where(b => b.TasksID == id);
        }
        
        
        
        private void GetPriorities()
        {
            IEnumerable<SelectListItem> Prios;
            Prios = new[]
                  {
                    new SelectListItem { Value = "1", Text = "High" },
                    new SelectListItem { Value = "2", Text = "Normal" },
                    new SelectListItem { Value = "3", Text = "Low" }
                  };
            ViewBag.TasksPriorities = Prios;

        }


        private void GetEmployees()
        {
            ViewBag.Employees =
            (from Employees in db.EmployeeModels.ToArray()
             select new SelectListItem
             {
                 Text = Employees.FirstName + " " + Employees.LastName,
                 Value = Employees.Employee_ID.ToString()
             }).ToArray();
        }

        private void GetCustomers()
        {
            ViewBag.Customers =
             (from Customers in db.CustomerModels.ToArray()
              select new SelectListItem
              {
                  Text = Customers.First_Name + " " + Customers.Last_Name + " - (" + Customers.Business_Name + ")",
                  Value = Customers.CustomerId.ToString()
              }).ToArray();
        }

        // POST: /Task/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "TasksID,Name,StartDate,DueDate,Complete,Description,Priority,Status,AssignementDate,CreationDate,Employee_ID,CustomerID")] TasksModel tasksmodel, FormCollection form)
        {
            if (ModelState.IsValid)
            {
                tasksmodel.TasksID = Guid.NewGuid().ToString();
                tasksmodel.CreationDate = DateTime.Now;
                db.Tasks.Add(tasksmodel);
                db.SaveChanges();
                
                //Check if the user uploaded a file or not
                if (form["fileUpload"].ToString().Length > 0)
                {
                    CreateFileModel(tasksmodel, form);
                    return RedirectToAction("Upload", "File", new { taction = "index",tcontroller = "Task" });
                }
                return RedirectToAction("index");
            }

            ViewBag.CustomerID = new SelectList(db.CustomerModels, "CustomerId", "CustomerId", tasksmodel.CustomerID);
            ViewBag.EmployeeID = new SelectList(db.EmployeeModels, "Employee_Id", "Employee_Id", tasksmodel.Employee_ID);
           
            return View(tasksmodel);
        }

        private void CreateFileModel(TasksModel tasksmodel, FormCollection form)
        {
            var Userid = (from d in db3.Customers where d.CustomerId == tasksmodel.CustomerID select d).FirstOrDefault().UserId;
            var UserName = (from d in db2.Users where d.Id == Userid select d).FirstOrDefault().UserName;


            //return RedirectToAction("Index");
            FileModel filemodel = new FileModel()
            {
                CustomerID = tasksmodel.CustomerID,
                Name = Path.GetFileName(form["fileUpload"].ToString()),
                UploadDate = DateTime.Now,
                Path = form["fileUpload"].ToString(),
                TasksID = tasksmodel.TasksID,
                FolderPath = UserName + "/" + tasksmodel.Name

            };
            TempData["Filemodel"] = filemodel;
        }

        // GET: /Task/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            TasksModel tasksmodel = db.Tasks.Find(id);
            if (tasksmodel == null)
            {
                return HttpNotFound();
            }
            GetCustomers();
            GetEmployees();
            return View(tasksmodel);
        }

        // POST: /Task/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "TasksID,Name,StartDate,DueDate,Complete,Description,Priority,Status,AssignementDate,CreationDate,Employee_ID,CustomerID")] TasksModel tasksmodel, FormCollection form)
        {
            if (ModelState.IsValid)
            {
                db.Entry(tasksmodel).State = EntityState.Modified;
                db.SaveChanges();
                //Check if the user uploaded a file or not
                if (form["fileUpload"].ToString().Length > 0)
                {
                    CreateFileModel(tasksmodel, form);
                    return RedirectToAction("Upload", "File", new { taction = "index", tcontroller = "Task" });
                }
                return RedirectToAction("Index");
            }
            GetCustomers();
            GetEmployees();
            return View(tasksmodel);
        }

        // GET: /Task/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            TasksModel tasksmodel = db.Tasks.Find(id);
            if (tasksmodel == null)
            {
                return HttpNotFound();
            }
            GetCustomers();
            GetEmployees();
            return View(tasksmodel);
        }

        // POST: /Task/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            TasksModel tasksmodel = db.Tasks.Find(id);
            db.Tasks.Remove(tasksmodel);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
        



        private void DropBox()
        {

           

        }











    }
}

